package com.lyj.mall.exception;

import com.lyj.mall.enums.ResponseEnum;
import com.lyj.mall.vo.ResponseVo;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLSyntaxErrorException;
import java.util.Objects;

import static com.lyj.mall.enums.ResponseEnum.*;

/**
 * @author lyj
 * @date 2019/12/19 23:03
 */
@ControllerAdvice
public class RuntimeExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN) // 设置http状态码
    public @ResponseBody
    ResponseVo handler(RuntimeException exception) {
        return ResponseVo.error(ERROR, exception.getMessage());
    }

    @ExceptionHandler(AuthorizationException.class)
    public @ResponseBody
    ResponseVo catchAuthorizationException() {
        return ResponseVo.error(ERROR, NOT_ROLE.getDesc());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public @ResponseBody
    ResponseVo notValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Objects.requireNonNull(result.getFieldError());
        return ResponseVo.error(PARAMETER_ERROR, result.getFieldError().getField() + " " +
                result.getFieldError().getDefaultMessage());
    }
    // SQLSyntaxErrorException
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public @ResponseBody
    ResponseVo SQLSyntaxErrorException(BadSqlGrammarException e) {
        return ResponseVo.error(SQL_ERROR);
    }
}
